<?php

namespace app\common\service;


use app\common\helper\FormatHelper;
use plugins\ALiYun\VoiceClass;
use plugins\FeiE\FeiEPrintClass;
use think\Db;

/**
 * 本地打印服务
 *
 * Class FeiEPrintService
 * @package app\common\service
 */
class PrintService
{

    /**
     * 打印手机充值账单
     */
    public static function printPhoneEntry($data,$user_info) {

        $fei_e_sn = Db::name('qt_store_printer')->where('store_id',$user_info['store_id'])->value('sn');
        $fei_e_sn = [];
        if (empty($fei_e_sn)) {
            return FormatHelper::fReturn('没有找到打印机数据','',204);
        }
        $card_data = Db::name('qt_viper_card_recharge_log')->alias('log')
            ->field([
                'log.*',
                'qvc.card_no',
                'qvt.name as card_type_name',
                'qvc.give_total_amount',//赠送总金额
                'qvc.give_amount',
                'qvc.total_amount',
                'qvc.amount',//会员余额 可用余额
                'qvc.mobile',//会员卡手机号
            ])
            ->leftJoin('qt_viper_card qvc','log.viper_card_id = qvc.id')
            ->leftJoin('qt_viper_type qvt','qvc.viper_type_id = qvt.id')
            ->where('qvc.id',$data['viper_card_id'])->where('log.id',$data['recharge_log_id'])->find();

        $store_name = Db::name('qt_store')->where('id',$card_data['store_id'])->value('name')??'';
        $real_name = Db::name('qt_users')->where('id',$card_data['user_id'])->value('real_name')??'';

        if ($card_data['card_type'] == 1) {
            $template_data = Db::name('qt_viper_recharge_template')->where(['id'=>$card_data['recharge_tempid']])->find();
        }
        if ($card_data['card_type'] == 2) {
            $template_data = Db::name('qt_viper_number_card_template')->where(['id'=>$card_data['recharge_tempid']])->find();
        }
        if ($card_data['card_type'] == 3) {
            $template_data = Db::name('qt_viper_month_card_template')->where(['id'=>$card_data['recharge_tempid']])->find();
        }
        $pay_type_config = Db::name('qt_pay_type')->column('id,name','id');

        $sale_data = Db::name('qt_users')->where('id',$card_data['sale_id'])->find();

        //上次余额
        $money_log_data = Db::name('qt_viper_money_log')->where([
            'chock_order_id'=>$card_data['order_no'],
            'type'=>1,//变更类型 1 充值 2 转账 3 消费
            'flag'=>1,//类型 1=账户余额 2=积分 3 赠送金额
        ])->find();
        $last_balance = !empty($money_log_data) ? $money_log_data['after_money'] - $money_log_data['money'] : 0 ;
        $payType  = json_decode($card_data['pay_content'],true);
        $payName = '';
        foreach ($payType as $key=>$value){
            $payName.= $value['pay_type']."(".$value['pay_money'].")";
        }
        $print_class = new FeiEPrintClass();
        $content  = '<CB>会员卡充值单</CB><BR>';
        $content .= '<C>单号：'.$card_data['card_no'].'</C><BR>';
        $content .= '<BOLD>打印时间：　　　　　    '.date('Y-m-d H:i:s').'</BOLD><BR>';
        $content .= '<BOLD>充值时间：　　　　　    '.date('Y-m-d H:i:s').'</BOLD><BR>';
        $content .= '电话：　　　　　             '.$card_data['mobile'].'<BR>';
        $content .= '卡类型：       　　　　　          '.$card_data['card_type_name'].'<BR>';
        $content .= '卡号：　　　　　              '.$card_data['card_no'].'<BR>';
        $content .= '所属门店：                        '.$store_name.'<BR>';
        $content .= '姓名：　　　　　                  '.$real_name.'<BR>';
        $content .= '---------------------------------------------<BR>';
        $content .= '充值模版：　　　　　          '.$template_data['name']??''.'<BR>';
        $content .= '充值金额：　　　　　                  '.$template_data['amount']??''.'<BR>';
        $content .= '赠送金额：　　　　　                   '.$card_data['give_amount'].'<BR>';
        $content .= '入卡金额：　　　　　                  '.$card_data['card_amount'].'<BR>';
        $content .= '上次余额：　　　　　                     '.$last_balance.'<BR>';
        $content .= '本金余额：　　　　　                     '.$card_data['amount'].'<BR>';
        $content .= '赠送金余额：　　　　　                 '.$card_data['give_total_amount'].'<BR>';
        $content .= '可用余额：　　　　　                  '.$card_data['amount'].'<BR>';
        $content .= '销售人：　　　　　               '.$sale_data['work_number'].'('.$sale_data['real_name'].')'.'<BR>';
        $content .= '--------------------------------------------<BR>';
        $content .= '付款说明：　　　　　            '.$card_data['recharge_content'].'<BR>';
        $content .= $payName.'<BR>';
        $content .= '--------------------------------------------<BR>';
        $content .= '单注/签字：____________________________<BR>';

        $result = $print_class->printMsg($fei_e_sn,$content,1);
        $result = json_decode($result,true);
        if ($result['ret'] == 0) {
            return FormatHelper::fReturn('打印成功','',200);
        }else {
            return FormatHelper::fReturn('打印失败','',204);
        }
    }



    /**
     * 打印手机结账账单
     */
    public static function printPcBill($check_out_id,$user_info) {
        $item = Db::name('qt_check_out')
            ->alias('out')
            ->field([
                'out.id',//结账单ID
                'out.order_no',//账单号
                'out.is_revoke',//状态
                'out.revoke_time',//撤销时间
                'out.revoke_person',//撤销人
                'out.revoke_remarks',//撤销备注
                'out.cashier_id',//结账人
                'out.cashier_time',//结账时间
                'out.pay_content',//付款方式
                'out.total_money',//总金额
                'out.payment_money',//实际支付
                'out.goods_order',//商品订单
                'out.project_order',//项目订单
                'out.uv_id',//商品订单
                'out.room_id',//房间ID
                'out.discount',//折免金额
            ])
            ->where([
                'out.id'=>$check_out_id,
                'out.store_id'=> $user_info['store_id'],
            ])->find();
        if (empty($item)) {
            return FormatHelper::fReturn('没有找到数据','',204);
        }
        $item['project_detail'] = [];//项目
        $item['product_detail'] = [];//商品
        $item['cashier_name'] = Db::name('qt_users')->where('id', $item['cashier_id'])->value('real_name');//结账人
        //结账详情
        $item_data = Db::name('qt_check_out_item')->where('check_out_id', $item['id'])->select();
        if (empty($item_data)) {
            return FormatHelper::fReturn('没有找到结账单详情数据','',204);
        }
        foreach ($item_data as $key => $val) {
            $data = [];
            //项目
            if (!empty($val['link_type']) && $val['link_type'] == 1) {
                $project_data = Db::name('qt_order_project')
                    ->where('project_id', $val['link_id'])
                    ->whereIn('id',$val['link_order_id'])
                    ->column('id,room_id,engineer_id,project_id,hand_card_id,name as project_name,order_type,is_add,num,price,payment_price,start_time,real_end_time,created_time', 'project_id');
                if (empty( $project_data[$val['link_id']] )) {
                    continue;
                }
                $project_item = $project_data[$val['link_id']];
                $data['project_name'] = $project_item['project_name'] ?? '';
                $engineer_data =  Db::name('qt_users')->where('id', $project_item['engineer_id'])->find();
                $data['engineer_name'] = $engineer_data['real_name'] ??'';
                $data['work_number'] = $engineer_data['work_number'] ??'';
                $data['engineer_id'] = $project_item['engineer_id'] ?? '';
                $data['hand_card_name'] = Db::name('qt_hand_card')->where('id',$project_item['hand_card_id'])->value('name') ??'';

                $data['room_id'] = $project_item['room_id'] ?? '';
                $data['room_name'] = Db::name('qt_room')->where('id', $project_item['room_id'])->value('name') ?? '';
                $data['order_type'] = $project_item['order_type'] ?? '';
                $data['is_add'] = $project_item['is_add'] ?? '';

                $data['num'] = $project_item['num']??'';
                $data['total_price'] = $project_item['price']??'';
                $data['payment_price'] = $project_item['payment_price']??'';
                $data['created_time'] = $project_item['created_time']??0;
                $data['real_end_time'] = $project_item['real_end_time']??0;
                $data['start_time'] = $project_item['start_time']??0;
                $item['project_detail'][] = $data;
            }
            //商品
            if (!empty($val['link_type']) && $val['link_type'] == 2) {
                $product_data = Db::name('qt_product_order_item')
                    ->alias('i')
                    ->leftJoin('qt_product_order o','i.order_id=o.id')
                    ->whereIn('o.id', explode(',',$item['goods_order']))//订单ID
                    ->where('i.goods_id', $val['link_id'])//订单ID
                    ->column('o.id,o.room_id,o.engineer_id,i.goods_id as project_id,
                    o.hand_card_id,i.goods_name as project_name,i.goods_num,i.goods_price,i.goods_total_price,o.total_price,o.payment_price,i.create_time,i.business_type', 'i.goods_id');
                if (empty($product_data[$val['link_id']])) {
                    continue;
                }
                $product_item = $product_data[$val['link_id']];

                $engineer_data =  Db::name('qt_users')->where('id', $product_item['engineer_id'])->find();//技师
                $data['engineer_name'] = $engineer_data['real_name'] ??'';
                $data['work_number'] = $engineer_data['work_number'] ??'';
                $data['engineer_id'] = $product_item['engineer_id'] ?? '';
                $data['hand_card_name'] = Db::name('qt_hand_card')->where('id',$product_item['hand_card_id'])->value('name')??'';

                $data['project_name'] = $product_item['project_name'] ?? '';
                $data['room_id'] = $product_item['room_id'] ?? '';
                $data['room_name'] = Db::name('qt_room')->where('id', $product_item['room_id'])->value('name') ?? '';
                $data['order_type'] = '';
                $data['is_add'] = '';
                $data['num'] = $product_item['goods_num']??'';
                $data['total_price'] = $product_item['total_price']??'';
                $data['payment_price'] = $product_item['payment_price']??'';
                $data['create_time'] = $product_item['create_time']??'';
                $data['business_type'] = $product_item['business_type']??'';
                $data['goods_price'] = $product_item['goods_price']??'';
                $data['goods_total_price'] = $product_item['goods_total_price']??'';
                $item['product_detail'][] = $data;
            }
        }
        $room_created_time = Db::name('qt_room_log')->where('room_id',$item['room_id'])->order('id desc')->value('created_time');
        $store_name = Db::name('qt_store')->where('id',$user_info['store_id'])->value('name');
        $total_price = 0;
        $payment_price = 0;
        foreach ($item['project_detail'] as $k => &$v) {
            $total_price = $total_price + $v['total_price'];
            $v['payment_price'] = empty( $v['payment_price']) ? 0 :  $v['payment_price'];
            $payment_price = $payment_price + $v['payment_price'];
        }
        foreach ($item['product_detail'] as $key => &$val) {
            $total_price = $total_price + $val['total_price'];
            $val['payment_price'] = empty( $val['payment_price']) ? 0 :  $val['payment_price'];
            $payment_price = $payment_price + $val['payment_price'];
            $item['product_detail'][$key]['business_type'] = 2 ? '【房费】' : '';
        }
        $result['check_out_id'] = $item['id'];
        $result['order_no'] = $item['order_no'];
        $result['pay_content'] = $item['pay_content'];
        $result['real_name'] = $user_info['real_name'];
        $result['check_out_id'] = $check_out_id;
        $result['project_detail'] = $item['project_detail'];
        $result['product_detail'] = $item['product_detail'];
        $result['total_price'] = $total_price;
        $result['payment_price'] = $total_price;
        $result['open_room_time'] = $room_created_time;
        $result['store_name'] = $store_name;
        $result['check_time'] = time();
        $result['print_time'] = time() + 1;
        $cardData = Db::name('qt_check_out_pay')
            ->field('c.card_no,vc.name as viper_type_name,c.name,c.mobile,pay.card_money,pay.card_give_money,pay.card_amount,pay.card_give_amount,c.score')
            ->alias('pay')
            ->leftJoin('qt_viper_card c','c.id = pay.viper_card_id')
            ->leftJoin('qt_viper_type vc','vc.id = c.viper_type_id')
            ->where(['pay.check_out_id'=>$check_out_id,'pay.pay_id'=>'6'])
            ->select();
        $result['card_data'] = $cardData;
        return $result;
    }


    /**
     * 挂账打印结账账单
     */
    public static function printPcBills($check_out_ids,$user_info) {
        $item = Db::name('qt_check_out')
            ->alias('out')
            ->field([
                'out.id',//结账单ID
                'out.order_no',//账单号
                'out.is_revoke',//状态
                'out.revoke_time',//撤销时间
                'out.revoke_person',//撤销人
                'out.revoke_remarks',//撤销备注
                'out.cashier_id',//结账人
                'out.cashier_time',//结账时间
                'out.pay_content',//付款方式
                'out.total_money',//总金额
                'out.payment_money',//实际支付
                'out.goods_order',//商品订单
                'out.project_order',//项目订单
                'out.uv_id',//商品订单
                'out.room_id',//房间ID
                'out.discount',//折免金额
            ])
            ->where(['out.store_id'=> $user_info['store_id']])
            ->whereIn('out.id',$check_out_ids)
            ->find();
        if (empty($item)) {
            return FormatHelper::fReturn('没有找到数据','',204);
        }
        $item['project_detail'] = [];//项目
        $item['product_detail'] = [];//商品
        $item['cashier_name'] = Db::name('qt_users')->where('id', $item['cashier_id'])->value('real_name');//结账人
        //结账详情
        $item_data = Db::name('qt_check_out_item')->whereIn('check_out_id', $check_out_ids)->select();
        if (empty($item_data)) {
            return FormatHelper::fReturn('没有找到结账单详情数据','',204);
        }
        foreach ($item_data as $key => $val) {
            $data = [];
            //项目
            if (!empty($val['link_type']) && $val['link_type'] == 1) {
                $project_data = Db::name('qt_order_project')
                    ->where('project_id', $val['link_id'])
                    ->whereIn('id',$val['link_order_id'])
                    ->column('id,room_id,engineer_id,project_id,hand_card_id,name as project_name,order_type,is_add,num,price,payment_price,start_time,real_end_time,created_time', 'project_id');
                if (empty( $project_data[$val['link_id']] )) {
                    continue;
                }
                $project_item = $project_data[$val['link_id']];
                $data['project_name'] = $project_item['project_name'] ?? '';
                $engineer_data =  Db::name('qt_users')->where('id', $project_item['engineer_id'])->find();
                $data['engineer_name'] = $engineer_data['real_name'] ??'';
                $data['work_number'] = $engineer_data['work_number'] ??'';
                $data['engineer_id'] = $project_item['engineer_id'] ?? '';
                $data['hand_card_name'] = Db::name('qt_hand_card')->where('id',$project_item['hand_card_id'])->value('name') ??'';

                $data['room_id'] = $project_item['room_id'] ?? '';
                $data['room_name'] = Db::name('qt_room')->where('id', $project_item['room_id'])->value('name') ?? '';
                $data['order_type'] = $project_item['order_type'] ?? '';
                $data['is_add'] = $project_item['is_add'] ?? '';

                $data['num'] = $project_item['num']??'';
                $data['total_price'] = $project_item['price']??'';
                $data['payment_price'] = $project_item['payment_price']??'';
                $data['created_time'] = $project_item['created_time']??0;
                $data['real_end_time'] = $project_item['real_end_time']??0;
                $data['start_time'] = $project_item['start_time']??0;
                $item['project_detail'][] = $data;
            }
            //商品
            if (!empty($val['link_type']) && $val['link_type'] == 2) {
                $product_data = Db::name('qt_product_order_item')
                    ->alias('i')
                    ->leftJoin('qt_product_order o','i.order_id=o.id')
                    ->where('i.id', $val['link_order_id'])//订单ID
                    ->column('o.id,o.room_id,o.engineer_id,i.goods_id as project_id,
                    o.hand_card_id,i.goods_name as project_name,i.goods_num,i.goods_price,i.goods_total_price,o.total_price,o.payment_price,i.create_time,i.business_type', 'i.goods_id');
                if (empty($product_data[$val['link_id']])) {
                    continue;
                }
                $product_item = $product_data[$val['link_id']];

                $engineer_data =  Db::name('qt_users')->where('id', $product_item['engineer_id'])->find();//技师
                $data['engineer_name'] = $engineer_data['real_name'] ??'';
                $data['work_number'] = $engineer_data['work_number'] ??'';
                $data['engineer_id'] = $product_item['engineer_id'] ?? '';
                $data['hand_card_name'] = Db::name('qt_hand_card')->where('id',$product_item['hand_card_id'])->value('name')??'';

                $data['project_name'] = $product_item['project_name'] ?? '';
                $data['room_id'] = $product_item['room_id'] ?? '';
                $data['room_name'] = Db::name('qt_room')->where('id', $product_item['room_id'])->value('name') ?? '';
                $data['order_type'] = '';
                $data['is_add'] = '';
                $data['num'] = $product_item['goods_num']??'';
                $data['total_price'] = $product_item['total_price']??'';
                $data['payment_price'] = $product_item['payment_price']??'';
                $data['create_time'] = $product_item['create_time']??'';
                $data['business_type'] = $product_item['business_type']??'';
                $data['goods_price'] = $product_item['goods_price']??'';
                $data['goods_total_price'] = $product_item['goods_total_price']??'';
                $item['product_detail'][] = $data;
            }
        }
        $room_created_time = Db::name('qt_room_log')->where('room_id',$item['room_id'])->order('id desc')->value('created_time');
        $store_name = Db::name('qt_store')->where('id',$user_info['store_id'])->value('name');
        $total_price = 0;
        $payment_price = 0;
        foreach ($item['project_detail'] as $k => &$v) {
            $total_price = $total_price + $v['total_price'];
            $v['payment_price'] = empty( $v['payment_price']) ? 0 :  $v['payment_price'];
            $payment_price = $payment_price + $v['payment_price'];
        }
        foreach ($item['product_detail'] as $key => &$val) {
            $total_price = $total_price + $val['total_price'];
            $val['payment_price'] = empty( $val['payment_price']) ? 0 :  $val['payment_price'];
            $payment_price = $payment_price + $val['payment_price'];
            if($val['business_type'] == '1'){
                $business = '';
            }else{
                $business = '【房费】';
            }
            $item['product_detail'][$key]['business_type'] = $business;
        }
        $result['check_out_id'] = $item['id'];
        $result['order_no'] = $item['order_no'];
        $result['pay_content'] = $item['pay_content'];
        $result['real_name'] = $user_info['real_name'];
        $result['check_out_id'] = $check_out_ids;
        $result['project_detail'] = $item['project_detail'];
        $result['product_detail'] = $item['product_detail'];
        $result['total_price'] = $total_price;
        $result['payment_price'] = $total_price;
        $result['open_room_time'] = $room_created_time;
        $result['store_name'] = $store_name;
        $result['check_time'] = time();
        $result['print_time'] = time() + 1;
        $cardData = Db::name('qt_check_out_pay')
            ->field('c.card_no,vc.name as viper_type_name,c.name,c.mobile,pay.card_money,pay.card_give_money,pay.card_amount,pay.card_give_amount,c.score')
            ->alias('pay')
            ->leftJoin('qt_viper_card c','c.id = pay.viper_card_id')
            ->leftJoin('qt_viper_type vc','vc.id = c.viper_type_id')
            ->where(['pay.check_out_id'=>$check_out_ids,'pay.pay_id'=>'6'])
            ->select();
        $result['card_data'] = $cardData;
        return $result;
    }



    /**
     * 打印PC小票
     */
    public static function printPc($data,$user_info) {

        $config = Db::name('qt_water_config')->where('store_id', $user_info['store_id'])->find();

        //水吧配置自动打印
        if (!empty($config['auto_print']) && $config['auto_print'] != 1) {
            return FormatHelper::fReturn('自动打印失败，水吧配置手动打印','',204);
        }
        $fei_e_sn = [];
        $fei_e_sn = Db::name('qt_store_printer')
            ->where('store_id',$user_info['store_id'])
            ->value('sn');
        if (empty($fei_e_sn)) {
            return FormatHelper::fReturn('没有找到打印机数据','',204);
        }

        //水吧配置不打印的商品分类
        if (!empty($config['noprint_product'])) {
            $productCate = explode(',', $config['noreceive_product']);//不接受的商品分类
            $productIds = Db::name('qt_product')->whereIn('product_category_id', $productCate)->column('id');
        }

        $print_class = new FeiEPrintClass();
        $room_no = Db::name('qt_room')->where('id',$data['room_id'])->value('name');
        $hand_card_no = Db::name('qt_hand_card')->where('id',$data['hand_card_id'])->value('name');
        $content = '<CB>小票打印</CB><BR>';
        $content .= '商品名称     数量       金额<BR>';
        $content .= '---------------------------------------------<BR>';

        $goodsRes = json_decode($data['goods'], true);
        $goods_total_price = 0;
        foreach ($goodsRes as $key => $val) {

            if (!empty($productIds) && in_array($productIds,$val['id'])) {
                continue;
            }
            $content .= "{$val['product_name']}         {$val['num']}        {$val['goods_total_price']}<BR>";
            $goods_total_price = $goods_total_price + $val['goods_total_price'];
        }
        $content .= '---------------------------------------------<BR>';
        $content .= "房间号: {$room_no}<BR>";
        //$content .= "手牌: {$hand_card_no}<BR>";
        $content .= '---------------------------------------------<BR>';
        $content .= "合计: ￥{$goods_total_price} 元<BR>";
        $content .= "下单时间: ".date("Y-m-d H:i:s",time()).'<BR>';
        $content .= "下单人: ({$user_info['work_number']}){$user_info['real_name']}<BR>";
        $result = $print_class->printMsg($fei_e_sn,$content,$config['print_number'] ?? 1);
        $result = json_decode($result,true);
        if ($result['ret'] == 0) {

            //水吧配置打印并确认
            if (!empty($config['print_confirm']) && $config['print_confirm'] == 1) {
                Db::name('qt_product_order_item')->where('order_id', $data['order_id'])->update(['is_send' => 1]);
            }

            return FormatHelper::fReturn('打印成功','',200);
        }else {
            return FormatHelper::fReturn('打印失败','',204);
        }
        return FormatHelper::fReturn('参数错误','',204);

    }


}